<template>
  <view class="chat-container">
    <!-- 聊天消息列表 -->
    <scroll-view :scroll-y="true" class="chat-content" :scroll-into-view="scrollToBottom">
      <view
        v-for="(item, index) in selectInfo.msg"
        :key="index"
        :class="{'my-msg': item.isSelf, 'other-msg': !item.isSelf}"
        :id="'msg-' + index"
      >
        <text class="user-name">{{ item.name }}</text>
        <text class="msg-text">{{ item.msg }}</text>
      </view>
    </scroll-view>

    <!-- 输入框和发送按钮 -->
    <view class="chat-input">
      <input
        v-model="message"
        placeholder="请输入消息..."
        confirm-type="send"
        @confirm="sendMsg"
      />
      <button @tap="sendMsg">发送</button>
    </view>
  </view>
</template>

<script>
import WebSocketClass from "@/config/websocket.js";

export default {
  data() {
    return {
      message: "",
      selectInfo: { msg: [] },
      scrollToBottom: ""
    };
  },
  mounted() {
    this.initWebSocket();
  },
  methods: {
    initWebSocket() {
      const ws = new WebSocketClass({
        serverUrl: `ws://192.168.1.30:5000/cloudBusiness/ws/message/37`,
      });

      ws.getMsg((data) => {
        console.log("收到服务器消息:", data);
        this.addMessage(data.name, data.msg, false);
      });

      this.ws = ws;
    },
    sendMsg() {
      if (!this.message.trim()) return;
			console.log(this.message,'123456');
			
      this.addMessage("我", this.message, true);
      this.ws.sendMsg(JSON.stringify({ msg: this.message }));
      this.message = "";
    },
    addMessage(name, msg, isSelf) {
      this.selectInfo.msg.push({ name, msg, isSelf });
      this.$nextTick(() => {
        this.scrollToBottom = 'msg-' + (this.selectInfo.msg.length - 1);
      });
    }
  },
  onUnload() {
    this.ws.closeSocket();
  }
};
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}
.chat-content {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}
.my-msg {
  text-align: right;
  color: #fff;
  background-color: #4caf50;
  padding: 8px 12px;
  border-radius: 10px;
  display: inline-block;
  margin: 5px 0;
}
.other-msg {
  text-align: left;
  color: #333;
  background-color: #e0e0e0;
  padding: 8px 12px;
  border-radius: 10px;
  display: inline-block;
  margin: 5px 0;
}
.user-name {
  font-size: 12px;
  color: #999;
  display: block;
  margin-bottom: 2px;
}
.msg-text {
  font-size: 14px;
}
.chat-input {
  display: flex;
  padding: 10px;
  border-top: 1px solid #ddd;
  background: #fff;
}
input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}
button {
  margin-left: 10px;
  background-color: #4caf50;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 5px;
  font-size: 14px;
}
</style>
